package com.eystar.pdc.directive;

import java.util.Set;

import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.eystar.pdc.model.User;
import com.eystar.pdc.util.LoginUtil;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * <pre>
 * 是否有auth权限标识，返回的是json对象
 * #auth_json("tag1","tag2")
 * 输出结果为 {tag1:true,tag2:false} , 
 * false表示无权限，true表示有权限
 * </pre>
 * @author Administrator
 *
 */
public class AuthJsonDirective extends Directive {
	
	public void setExprList(ExprList exprList) {
		int len = exprList.length();
		if (len < 1) {
			throw new ParseException("指令#auth_json最少有一个参数", location);
		}
		super.setExprList(exprList);
	}
	
	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		JSONObject object = new JSONObject();
		HttpSession session = (HttpSession) scope.get("session");
		User user = (User) session.getAttribute(LoginUtil.SESSION_CURRENT_USER);
		if (user != null) {
			Set<String> authorities = user.get("authorities");
			for (Expr expr : exprList.getExprArray()) {
				String authTag = (String) expr.eval(scope);
				object.put(authTag, authorities.contains(authTag));
			}
		}
		write(writer, object.toJSONString());
	}

}
